package com.web.kdl.service.HistoryEvent;

import com.web.kdl.common.result.CommonResult;
import com.web.kdl.dao.historyEvent.HistoryEventDao;
import com.web.kdl.daoV2.siteWheel.SiteWheelDao;
import com.web.kdl.entity.historyEvent.HistoryEvent;
import com.web.kdl.pojo.Vo.ExportTaskVO;
import com.web.kdl.pojo.form.DataReportForm;
import com.web.kdl.pojo.form.HistoryEventForm;
import com.web.kdl.service.createTable.TableType;
import com.web.kdl.service.excel.ExcelService;
import com.web.kdl.service.excel.ExportTaskManager;
import com.web.kdl.service.site.SiteService;
import com.web.kdl.util.TableNameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author： shulibin
 * @Date： 2025/7/18 11:18
 * @Describe：
 */
@Service
public class HistoryEventServiceImpl implements HistoryEventService {
    @Resource
    private HistoryEventDao HistoryEventDao;
    @Resource
    SiteWheelDao siteWheelDao;
    @Resource
    SiteService siteService;
    @Autowired
    private ExcelService excelService;
    @Resource
    ExportTaskManager taskManager;
    @Override
    public List<HistoryEvent> getAllHistoryEvent() {
        ArrayList<HistoryEvent> historyEvents = new ArrayList<>();
        List<String> allStatusTableName = siteService.getAllSiteName(TableType.STATUS);
        allStatusTableName.forEach(tableName -> {
            List<HistoryEvent> dataReports = HistoryEventDao.selectAllHistoryEvent(tableName);
            historyEvents.addAll(dataReports);
        });
        return historyEvents;
    }

    @Override
    public List<Map<String, Object>> getHistoryEvent(HistoryEventForm historyEventForm) {
        ArrayList<HistoryEvent> historyEvents = new ArrayList<>();
        List<String> allStatusTableName = siteService.getAllSiteName(TableType.STATUS);
        allStatusTableName.forEach(tableName -> {
            List<HistoryEvent> dataReports = HistoryEventDao.selectAllHistoryEventByTime(tableName,historyEventForm.getStartTime(),historyEventForm.getEndTime());
            historyEvents.addAll(dataReports);
        });

        // 导出文件
        excelService.exportHistoryEventExcel(historyEvents,historyEventForm);
        List<Map<String, Object>> method = method(historyEvents);
        return method;
    }



    private List<Map<String, Object>> method(List<HistoryEvent> historyEvents) {
        List<Map<String, Object>> result = new ArrayList<>();

        // 一级分组：sum_site
        Map<String, List<HistoryEvent>> bySumSite = historyEvents.stream()
                .collect(Collectors.groupingBy(HistoryEvent::getSumSite));

        for (Map.Entry<String, List<HistoryEvent>> sumEntry : bySumSite.entrySet()) {
            String sumSite = sumEntry.getKey();
            List<HistoryEvent> sumSiteReports = sumEntry.getValue();

            Map<String, Object> sumSiteMap = new HashMap<>();
            sumSiteMap.put("name", sumSite);
            List<Map<String, Object>> subSites = new ArrayList<>();

            // 二级分组：sub_site
            Map<String, List<HistoryEvent>> bySubSite = sumSiteReports.stream()
                    .collect(Collectors.groupingBy(HistoryEvent::getSubSite));

            for (Map.Entry<String, List<HistoryEvent>> subEntry : bySubSite.entrySet()) {
                String subSite = subEntry.getKey();
                List<HistoryEvent> subSiteReports = subEntry.getValue();

                Map<String, Object> subSiteMap = new HashMap<>();
                subSiteMap.put("name", subSite);
                List<Map<String, Object>> dataNames = new ArrayList<>();

                // 三级分组：data_name（替换原先的 device_name）
                Map<String, List<HistoryEvent>> byDataName = subSiteReports.stream()
                        .collect(Collectors.groupingBy(HistoryEvent::getDeviceName));

                for (Map.Entry<String, List<HistoryEvent>> dataNameEntry : byDataName.entrySet()) {
                    String dataName = dataNameEntry.getKey();
                    List<HistoryEvent> dataList = dataNameEntry.getValue();

                    Map<String, Object> dataNameMap = new HashMap<>();
                    dataNameMap.put("name", dataName);
                    dataNameMap.put("data", dataList); // 最底层原始数据列表

                    dataNames.add(dataNameMap);
                }

                subSiteMap.put("children", dataNames);
                subSites.add(subSiteMap);
            }

            sumSiteMap.put("children", subSites);
            result.add(sumSiteMap);
        }
        return result;
    }

    @Override
    public CommonResult submitExportTask(DataReportForm dataReportForm) {
        // 生成任务ID
        String taskId = UUID.randomUUID().toString();

        // 创建任务
        ExportTaskVO task = taskManager.createTask(taskId);

        // 获取表名
        String statusTableName = TableNameUtils.getStatusTableName(
                dataReportForm.getSiteName(),
                dataReportForm.getMatrixName(),
                dataReportForm.getFlyWheelName()
        );
        List<String> allStatusTableList = siteService.getAllSiteName(TableType.STATUS);
        // 异步执行导出
        excelService.exportHistoryEventExcelAsync(taskId, allStatusTableList, dataReportForm);

        return CommonResult.success(task);
    }

    
}
